/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package controller;

import java.io.File;
import java.io.FileFilter;
import java.net.URL;
import java.util.ArrayList;
import java.util.ResourceBundle;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import javafx.application.Platform;
import javafx.collections.FXCollections;
import javafx.collections.ListChangeListener;
import javafx.collections.ObservableList;
import javafx.event.EventHandler;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.geometry.Pos;
import javafx.scene.Cursor;
import javafx.scene.control.ScrollPane;
import javafx.scene.control.TreeCell;
import javafx.scene.control.TreeItem;
import javafx.scene.control.TreeView;
import javafx.scene.effect.Reflection;
import javafx.scene.image.ImageView;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.FlowPane;
import javafx.scene.layout.HBox;
import javafx.util.Callback;
import model.Album;
import model.Photo;
import model.myFileFilter;
import view.MyTreeCell;

/**
 *
 * @author LZH
 */
public class MainController implements Initializable {

    @FXML
    private TreeView treeView;

    @FXML
    private ImageView albumList;

    @FXML
    private FlowPane previewPane;

    @FXML
    private ScrollPane scrollPane;

    @FXML
    private FlowPane allAlbumPane;

    private ArrayList<Album> allAlbum;

    private String installedPath = "E:\\photoManager";

    public MainController() {

    }

    public TreeItem<File> CreateTreeRoot() {
        File[] disks = File.listRoots();
        TreeItem<File> root = createNode(new File("<<>>"));

        for (int i = 0; i < disks.length; i++) {
            if (disks[i].canExecute()) {
                TreeItem<File> disk = createNode(disks[i]);
                root.getChildren().add(disk);
            }
        }

        return root;
    }

    private TreeItem<File> createNode(final File f) {
        TreeItem treeItem = new TreeItem<File>(f) {
            private boolean isLeaf;
            private boolean isFirstTimeChildren = true;
            private boolean isFirstTimeLeaf = true;

            @Override
            public ObservableList<TreeItem<File>> getChildren() {
                if (isFirstTimeChildren) {
                    isFirstTimeChildren = false;
                    super.getChildren().setAll(buildChildren(this));
                }
                return super.getChildren();
            }

            @Override
            public boolean isLeaf() {
                if (isFirstTimeLeaf) {
                    isFirstTimeLeaf = false;
                    File f = (File) getValue();
                    isLeaf = f.isFile();
                }

                return isLeaf;
            }

            private ObservableList<TreeItem<File>> buildChildren(TreeItem<File> TreeItem) {
                File f = TreeItem.getValue();
                if (f != null && f.isDirectory()) {
                    File[] files = f.listFiles();
                    if (files != null) {
                        ObservableList<TreeItem<File>> children = FXCollections.observableArrayList();

                        for (File childFile : files) {
                            children.add(createNode(childFile));
                        }

                        return children;
                    }
                }

                return FXCollections.emptyObservableList();
            }
        };
        return treeItem;
    }

    @Override
    public void initialize(URL location, ResourceBundle resources) {
        treeView.setRoot(this.CreateTreeRoot());
        treeView.setCellFactory(new Callback<TreeView<File>, TreeCell<File>>() {
            @Override
            public TreeCell<File> call(TreeView<File> arg0) {
                return new MyTreeCell();
            }
        });
        this.allAlbum = Productor.allAlbumProductor();
        for (int i = 0; i < allAlbum.size(); i++) {
            ImageView imageView = new ImageView(allAlbum.get(i).getCover());
            imageView.setFitHeight(50);
            Reflection reflection = new Reflection();
            reflection.setFraction(0.2);
            reflection.setTopOpacity(0.3);
            imageView.setEffect(reflection);
            imageView.setPreserveRatio(true);
            imageView.setCursor(Cursor.HAND);
            imageView.setId("allAlbumId:" + i);
            EventHandler<MouseEvent> mousePressed = new EventHandler<MouseEvent>() {

                @Override
                public void handle(MouseEvent event) {
                    ImageView imageView = (ImageView) (event.getTarget());
                    String index = imageView.getId().substring(imageView.getId().lastIndexOf(":") + 1, imageView.getId().length());
//                    System.out.println(index);
                    int i = Integer.parseInt(index);
                    showAlbum(MainController.this.allAlbum.get(i));
                }

            };
            imageView.setOnMousePressed(mousePressed);
            HBox hbox = new HBox();
            hbox.getChildren().add(imageView);
            hbox.setAlignment(Pos.CENTER);
            hbox.setMinHeight(65);
            hbox.setMinWidth(95);
            this.allAlbumPane.getChildren().add(hbox);
        }
        treeView.getSelectionModel().getSelectedItems().addListener((ListChangeListener.Change c) -> {
            if (c.getList() != null
                    && c.getList().get(0) != null
                    && ((TreeItem) c.getList().get(0)).getValue() != null) {
                TreeItem treeItem = (TreeItem) (c.getList().get(0));
                File file = (File) (treeItem.getValue());
                if (file.isDirectory()) {
                    myFileFilter fileFilter = new myFileFilter();
                    File[] files = file.listFiles(fileFilter);
                    MyRunnable runnable = new MyRunnable(files,this.previewPane);
                    Platform.runLater(runnable);
            }
//                Album album = loadAlbum(file.getAbsolutePath());
//                this.previewPane.getChildren().remove(0, this.previewPane.getChildren().size());
//                if(album != null){
//                    for(int i = 0; i < album.getInnerPhoto().size(); i++){
//                        Photo photo = (Photo)(album.getInnerPhoto().get(i));
//                        ImageView imageView = new ImageView(photo.getPhoto());
//                        imageView.setFitHeight(70);  
//                         Reflection reflection = new Reflection();
//                         reflection.setFraction(0.2);
//                         reflection.setTopOpacity(0.3);
//                        imageView.setEffect(reflection);
////                        imageView.set
//                        imageView.setPreserveRatio(true); 
//                        HBox hbox = new HBox();
//                        hbox.getChildren().add(imageView);
//                        hbox.setAlignment(Pos.CENTER);
////                        hbox.setBorder(Border.EMPTY);
//                        hbox.setMinHeight(100);
//                        hbox.setMinWidth(150);
////                        Rectangle2D rectangle2D = new Rectangle2D(0, 0, 100, 70);                        
////                        imageView.setViewport(rectangle2D);     
//                        
////                        imageView.setSmooth(true);
//                        this.previewPane.getChildren().add(hbox);
//                    }                    
//                }

        }
    }

);
//        treeView.setOnKeyPressed(null);
    }
    
    public boolean isContainPhotos(String dirStr) {
        boolean flag = false;
        String[] strs = {".jpg", ".png", ".bmp", ".jpeg", ".gif"};
        File dir = new File(dirStr);
        if(dir.exists() && dir != null){
            FileFilter fileFilter = new FileFilter() {
                @Override
        public boolean accept(File file) {
                    //if the file extension is .txt return true, else false
                    if (file.getName().endsWith(".jpg")||
                            file.getName().endsWith(".jpeg") ||
                            file.getName().endsWith(".png") ||
                            file.getName().endsWith(".gif") ||
                            file.getName().endsWith(".bmp")) {
                        return true;
                    }
                    return false;
                }
            }; 
            File[] files = dir.listFiles(fileFilter);
            
            if(files != null){
                if(files.length > 0){
                    flag = true;
                }                
            }
//            for (File file : files) {
//                for (String str : strs) {
//                    if (file.isFile() && file.toString().endsWith(str)) {
//    //                    fileList.add(file.getAbsoluteFile());
//                        flag = true;
//                    }
//    //                if (file.isDirectory()) {
//    //                    findFileByEndStr(file.toString());
//                }
//            }           
        }

        return flag;
    }
    
    public boolean isInThumbnailsFolder(String path){
        String ThumbnailsPath = this.installedPath + path.substring(path.lastIndexOf("\\"), path.length());
        File file = new File(ThumbnailsPath);
        return  file.exists();
    }
    
    public Album loadAlbum(String path){
        Album album = null;
        if(isContainPhotos(path)){
            System.out.println("包含图片");
            if(isInThumbnailsFolder(path)){
                System.out.println("有缩略图文件夹");
                String ThumbnailsPath = this.installedPath + path.substring(path.lastIndexOf("\\"), path.length());
                album = Productor.albumProductor(ThumbnailsPath);
            }else{
                System.out.println("没有缩略图文件夹");
                String newPath = Productor.thumbnailsProductor(path);
                album = Productor.albumProductor(newPath);
            }
        }
        return album;
    }
    
    public void showAlbum(Album album){
        this.previewPane.getChildren().remove(0, this.previewPane.getChildren().size());
        for(int i = 0; i < album.getInnerPhoto().size(); i++){
            Photo photo = (Photo)(album.getInnerPhoto().get(i));
            ImageView imageView = new ImageView(photo.getPhoto());
            imageView.setFitHeight(70);  
             Reflection reflection = new Reflection();
             reflection.setFraction(0.2);
             reflection.setTopOpacity(0.3);
            imageView.setEffect(reflection);
//                        imageView.set
            imageView.setPreserveRatio(true); 
            HBox hbox = new HBox();
            hbox.getChildren().add(imageView);
            hbox.setAlignment(Pos.CENTER);
//                        hbox.setBorder(Border.EMPTY);
            hbox.setMinHeight(100);
            hbox.setMinWidth(150);
//                        Rectangle2D rectangle2D = new Rectangle2D(0, 0, 100, 70);                        
//                        imageView.setViewport(rectangle2D);     

//                        imageView.setSmooth(true);
            this.previewPane.getChildren().add(hbox);
            System.out.println();
        

}           
    }

}
class MyRunnable implements Runnable {

    File[] files;
    int i;
    FlowPane previewPane;

    public MyRunnable(File[] files, FlowPane previewPane) {
        this.files = files;
        this.i = i;
        this.previewPane = previewPane;
    }

    @Override
    public void run() {
        for(int i = 0; i < files.length; i++){
            this.originFileToPane(files[i]);
        }
    }

    public void originFileToPane(File file) {
        System.out.println(file.getName());
        File smallFile = Productor.sPhotoProduct(file);
        Photo photo = Productor.photoProductor(smallFile);
        ImageView imageView = new ImageView(photo.getPhoto());
        imageView.setFitHeight(70);
        Reflection reflection = new Reflection();
        reflection.setFraction(0.2);
        reflection.setTopOpacity(0.3);
        imageView.setEffect(reflection);
        imageView.setPreserveRatio(true);
        HBox hbox = new HBox();
        hbox.getChildren().add(imageView);
        hbox.setAlignment(Pos.CENTER);
        hbox.setMinHeight(100);
        hbox.setMinWidth(150);
        System.out.println(imageView.getImage().getWidth());
        this.previewPane.getChildren().add(hbox);
    }

}
